package com.yuanlrc.hotel;

import com.yuanlrc.common.config.Global;
import com.yuanlrc.common.config.ServerConfig;
import com.yuanlrc.common.core.domain.AjaxResult;
import com.yuanlrc.common.utils.file.FileUploadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/common/upload")
public class CommonUpload {


    @Autowired
    private ServerConfig serverConfig;

    /**
     * 通用上传请求
     */
    @PostMapping("/image")
    @ResponseBody
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        String uploadPhotoSufix = ".jpg,.png,.gif,.jpeg";
        long size = 2;

        //判断文件类型是否是图片
        String originalFilename = file.getOriginalFilename();
        //获取文件后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."),originalFilename.length());
        if(!uploadPhotoSufix.contains(suffix.toLowerCase())){
            return AjaxResult.error("文件类型不是图片");
        }

        if(file.getSize()/1024 > size){
            AjaxResult.error("文件大小不能超过2MB");
        }

        try
        {
            // 上传文件路径
            String filePath = Global.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("url", url);
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

}
